

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/fluid.png">
  <link rel="icon" href="/img/fluid.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="John Doe">
  <meta name="keywords" content="">
  
    <meta name="description" content="@[toc] 一、logback 简介官方文档：https:&#x2F;&#x2F;logback.qos.ch&#x2F;manual&#x2F; logback 是 继log4j（日志管理框架）推出后的升级版，由 log4j 的创始人 Ceki Gülcü 先生设计。 log back 相比于 log4j （官方文档指的是log4j 1.x 版本）的优势有（部分）：【具体请参考官方说明：https:&#x2F;&#x2F;logback.qos.ch&#x2F;">
<meta property="og:type" content="article">
<meta property="og:title" content="设计模式 笔记5 _ 工厂方法模式 在源码中的应用 _ logback 日志管理框架含义、架构以及配置 _ logback 使用案例 _ logback中存在的工厂方法模式和单例模式 _">
<meta property="og:url" content="http://example.com/2022/07/21/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F%20%E7%AC%94%E8%AE%B05%20_%20%E5%B7%A5%E5%8E%82%E6%96%B9%E6%B3%95%E6%A8%A1%E5%BC%8F%20%E5%9C%A8%E6%BA%90%E7%A0%81%E4%B8%AD%E7%9A%84%E5%BA%94%E7%94%A8%20_%20logback%20%E6%97%A5%E5%BF%97%E7%AE%A1%E7%90%86%E6%A1%86%E6%9E%B6%E5%90%AB%E4%B9%89%E3%80%81%E6%9E%B6%E6%9E%84%E4%BB%A5%E5%8F%8A%E9%85%8D%E7%BD%AE%20_%20logback%20%E4%BD%BF%E7%94%A8%E6%A1%88%E4%BE%8B%20_%20logback%E4%B8%AD%E5%AD%98%E5%9C%A8%E7%9A%84%E5%B7%A5%E5%8E%82%E6%96%B9%E6%B3%95%E6%A8%A1%E5%BC%8F%E5%92%8C%E5%8D%95%E4%BE%8B%E6%A8%A1%E5%BC%8F%20_/index.html">
<meta property="og:site_name" content="Hexo">
<meta property="og:description" content="@[toc] 一、logback 简介官方文档：https:&#x2F;&#x2F;logback.qos.ch&#x2F;manual&#x2F; logback 是 继log4j（日志管理框架）推出后的升级版，由 log4j 的创始人 Ceki Gülcü 先生设计。 log back 相比于 log4j （官方文档指的是log4j 1.x 版本）的优势有（部分）：【具体请参考官方说明：https:&#x2F;&#x2F;logback.qos.ch&#x2F;">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2022-07-21T06:38:13.000Z">
<meta property="article:modified_time" content="2022-08-22T15:41:17.833Z">
<meta property="article:author" content="John Doe">
<meta property="article:tag" content="设计模式">
<meta name="twitter:card" content="summary_large_image">
  
  
  
  <title>设计模式 笔记5 _ 工厂方法模式 在源码中的应用 _ logback 日志管理框架含义、架构以及配置 _ logback 使用案例 _ logback中存在的工厂方法模式和单例模式 _ - Hexo</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"example.com","root":"/","version":"1.9.2","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"follow_dnt":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
  


  
<meta name="generator" content="Hexo 6.2.0"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>尤 Ni&#39;s Blog</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/img/default.png') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="设计模式 笔记5 _ 工厂方法模式 在源码中的应用 _ logback 日志管理框架含义、架构以及配置 _ logback 使用案例 _ logback中存在的工厂方法模式和单例模式 _"></span>
          
        </div>

        
          
  <div class="mt-3">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-author" aria-hidden="true"></i>
        John Doe
      </span>
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2022-07-21 14:38" pubdate>
          2022年7月21日 下午
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          12k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          98 分钟
        
      </span>
    

    
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">设计模式 笔记5 _ 工厂方法模式 在源码中的应用 _ logback 日志管理框架含义、架构以及配置 _ logback 使用案例 _ logback中存在的工厂方法模式和单例模式 _</h1>
            
              <p class="note note-info">
                
                  
                    本文最后更新于：1 小时前
                  
                
              </p>
            
            
              <div class="markdown-body">
                
                <p>@[toc]</p>
<h1 id="一、logback-简介"><a href="#一、logback-简介" class="headerlink" title="一、logback 简介"></a>一、logback 简介</h1><p>官方文档：<a target="_blank" rel="noopener" href="https://logback.qos.ch/manual/">https://logback.qos.ch/manual/</a></p>
<p>logback 是 继log4j（日志管理框架）推出后的升级版，由 log4j 的创始人 Ceki Gülcü 先生设计。</p>
<p>log back 相比于 log4j （官方文档指的是log4j 1.x 版本）的优势有（部分）：【具体请参考官方说明：<a target="_blank" rel="noopener" href="https://logback.qos.ch/reasonsToSwitch.html">https://logback.qos.ch/reasonsToSwitch.html</a>】</p>
<blockquote>
<ol>
<li>运行速度更快，内存占用更小</li>
<li>logback-classic 组件实现了 SLF4J 原生的 API，所以 logback 可以用来替换使用 SLF4J 的项目</li>
<li>若更新了配置文件，logback-classic 可以自动快速地重新加载配置文件， 可动态扩展到每秒百万次的调用，分布在数百个线程上，不涉及创建单独的扫描线程</li>
<li>提供 I &#x2F; O 故障恢复机制，若文件服务器出现故障，则无需重启应用程序来恢复记录，当文件服务器恢复正常时，相关的  logback appender 会快速地从之前的故障状态中恢复（由LogbackFileAppender及其所有子类，包括RollingFileAppender实现）</li>
<li>自动删除旧的日志记录，可控制日志记录文件的最大数量以及最长保存时间，通过设置<a target="_blank" rel="noopener" href="https://logback.qos.ch/manual/appenders.html#TimeBasedRollingPolicy">TimeBasedRollingPolicy</a> 或<a target="_blank" rel="noopener" href="https://logback.qos.ch/manual/appenders.html#SizeAndTimeBasedFNATP">SizeAndTimeBasedFNATP的</a>maxHistory属性，默认时间单位是月</li>
</ol>
</blockquote>
<p>官方版本说明： <a target="_blank" rel="noopener" href="https://logback.qos.ch/news.html">https://logback.qos.ch/news.html</a></p>
<ul>
<li>Logback 官方于2021-08-10 发布 1.3.0-alpha7 版本 ，支持 Java8，Jetty 9.4.9 和 Tomcat 9.0.50</li>
<li>截止 2022 &#x2F; 07&#x2F; 21，最新的稳定 logback 版本是 1.2.11，支持 Java 8</li>
<li>官方 Maven 的仓库 groupId 为 ch.qos.logback</li>
</ul>
<p>logback 支持的日志级别与说明</p>
<table>
<thead>
<tr>
<th align="left">级别</th>
<th align="left">描述</th>
</tr>
</thead>
<tbody><tr>
<td align="left">TRACE</td>
<td align="left">在线调试，默认情况下，该级别日志既不打印到终端，也不输出到文件</td>
</tr>
<tr>
<td align="left">DEBUG</td>
<td align="left">终端查看，调试，默认情况下输出到终端，但不会归档到日志文件</td>
</tr>
<tr>
<td align="left">INFO</td>
<td align="left">记录程序进度和状态信息</td>
</tr>
<tr>
<td align="left">WARN</td>
<td align="left">警告信息</td>
</tr>
<tr>
<td align="left">ERROR</td>
<td align="left">状态错误，该错误发生后，程序仍可以运行</td>
</tr>
</tbody></table>
<p>日志级别：ERROR &gt; WARN&gt; INFO &gt; DEBUG &gt; TRACE</p>
<h1 id="二、logback-架构"><a href="#二、logback-架构" class="headerlink" title="二、logback 架构"></a>二、logback 架构</h1><hr>
<p>参考资料：<a target="_blank" rel="noopener" href="https://logback.qos.ch/manual/architecture.html">https://logback.qos.ch/manual/architecture.html</a><br>主要模块：logback主要分成三大模块，分别是：</p>
<ul>
<li>logback-core，框架的核心，其他两个模块依赖此模块</li>
<li>logback-classic，log4j优化版本，原生实现了 slf4j</li>
<li>logback-access，可集成到现有的 Servlet 容器，如 Tomcat 和 Jetty</li>
</ul>
<p>注：我们可以基于 logback-core 自定义模块<br>![](<a target="_blank" rel="noopener" href="https://img-blog.csdnimg.cn/img_convert/01ddffecc71fa31413e500dc020ea4df.jpeg#pic_center">https://img-blog.csdnimg.cn/img_convert/01ddffecc71fa31413e500dc020ea4df.jpeg#pic_center</a> &#x3D;70%x)</p>
<h2 id="2-1-logback-中主要的三个接口"><a href="#2-1-logback-中主要的三个接口" class="headerlink" title="2.1 logback 中主要的三个接口"></a>2.1 logback 中主要的三个接口</h2><p>logback主要支持三个接口：Logger、Appender 和 Layout，这三种类型的组件协同工作，使开发人员能根据消息类型和级别记录消息，并在运行时控制这些消息的格式和报告位置</p>
<p>接口 Logger 是 <code>logback-classic</code> 中的一部分，而 Appender 和 Layout 这两个接口是 <code>logback-core</code>的一部分，作为通用模块，logback-core里没有 Logger </p>
<h2 id="2-2-Logger-Context"><a href="#2-2-Logger-Context" class="headerlink" title="2.2 Logger Context"></a>2.2 Logger Context</h2><p>任何一个日志 API 都比原始的控制台打印 <code>System.out.println</code>更有优势，因为能禁用指定的日志语句，同时也允许其他日志语句不受影响地打印到控制台或文件，即支持多线程操作。</p>
<p>在 <code>logback-classic</code>模块中，这种分类是 loggers里的一部分，<br>LoggerContext  支持生成多个 logger，并存储到内部的一种<strong>树形</strong>结构中，每个独立的 logger 都需连接到 LoggerContext。</p>
<p>不同的 logger 具有不同的名称，而且是区分大小写的，通过符号点来区分父级和子级，比如<br>名为 <code>com.uni</code>是 <code>com.uni.Logger</code>的父级。</p>
<p>LoggerContext 中存在一个 <code>root logger</code>，其特点是位于 logger 树形层次结构的顶部，其他的logger都是 root logger的子节点，我们可通过 getLogger 方法获取</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">// final static String ROOT_LOGGER_NAME = &quot;ROOT&quot;;</span><br><span class="hljs-type">Logger</span> <span class="hljs-variable">rootLogger</span> <span class="hljs-operator">=</span> LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);<br></code></pre></td></tr></table></figure>
<h2 id=""><a href="#" class="headerlink" title=""></a></h2><p>Logger 接口的常用方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> org.slf4j; <br><span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title class_">Logger</span> &#123;<br><br>  <span class="hljs-comment">// Printing methods: </span><br>  <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">trace</span><span class="hljs-params">(String message)</span>;<br>  <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">debug</span><span class="hljs-params">(String message)</span>;<br>  <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">info</span><span class="hljs-params">(String message)</span>; <br>  <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">warn</span><span class="hljs-params">(String message)</span>; <br>  <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">error</span><span class="hljs-params">(String message)</span>; <br>&#125;<br></code></pre></td></tr></table></figure>
<h2 id="2-3-Logback中的日志级别"><a href="#2-3-Logback中的日志级别" class="headerlink" title="2.3 Logback中的日志级别"></a>2.3 Logback中的日志级别</h2><p>官方文档：<a target="_blank" rel="noopener" href="https://logback.qos.ch/manual/architecture.html">https://logback.qos.ch/manual/architecture.html</a><br>logback中的日志级别又称级别继承（Level Inheritance）<br>之前提到的日志级别均在 logback的 logback-classic模块中的 ch.qos.logback.classic.Level 内定义 </p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> ch.qos.logback.classic;<br><br><span class="hljs-keyword">import</span> java.io.Serializable;<br><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">Level</span> <span class="hljs-keyword">implements</span> <span class="hljs-title class_">Serializable</span> &#123; <br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-type">Level</span> <span class="hljs-variable">OFF</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Level</span>(<span class="hljs-number">2147483647</span>, <span class="hljs-string">&quot;OFF&quot;</span>);<br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-type">Level</span> <span class="hljs-variable">ERROR</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Level</span>(<span class="hljs-number">40000</span>, <span class="hljs-string">&quot;ERROR&quot;</span>);<br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-type">Level</span> <span class="hljs-variable">WARN</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Level</span>(<span class="hljs-number">30000</span>, <span class="hljs-string">&quot;WARN&quot;</span>);<br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-type">Level</span> <span class="hljs-variable">INFO</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Level</span>(<span class="hljs-number">20000</span>, <span class="hljs-string">&quot;INFO&quot;</span>);<br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-type">Level</span> <span class="hljs-variable">DEBUG</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Level</span>(<span class="hljs-number">10000</span>, <span class="hljs-string">&quot;DEBUG&quot;</span>);<br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-type">Level</span> <span class="hljs-variable">TRACE</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Level</span>(<span class="hljs-number">5000</span>, <span class="hljs-string">&quot;TRACE&quot;</span>);<br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-type">Level</span> <span class="hljs-variable">ALL</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Level</span>(-<span class="hljs-number">2147483648</span>, <span class="hljs-string">&quot;ALL&quot;</span>);<br>    ...<br>&#125;<br></code></pre></td></tr></table></figure>

<p><strong>日志级别机制：</strong> 如果创建的 Logger 没有分配级别，那么将从最近的祖先 Logger 那继承一个具有分配级别的 Logger ，即：</p>
<blockquote>
<p>给定 logger 的有效级别等于其树形层次结构的第一个非空级别，从 logger 本身开始并在层次结构中向上移动到 <code>root logger</code>，而 <code>root logger</code>默认级别为 DEBUG。</p>
</blockquote>
<p>所以当我们根据类创建 Logger 对象时，若没有指定级别，那么默认就为 LoggerContext 中 root logger 的 DEBUG 级别。</p>
<p>接下来是来自官方的四个级别继承案例：<a target="_blank" rel="noopener" href="https://logback.qos.ch/manual/architecture.html">https://logback.qos.ch/manual/architecture.html</a></p>
<p>【例1】自定义的 Logger 都未指定级别，那么默认继承 root logger 的默认 DEBUG级别</p>
<table>
<thead>
<tr>
<th>Logger 名称</th>
<th>指定的级别</th>
<th>实际的级别</th>
</tr>
</thead>
<tbody><tr>
<td>root</td>
<td>DEBUG（默认）</td>
<td>DEBUG</td>
</tr>
<tr>
<td>X</td>
<td>未指定</td>
<td>DEBUG</td>
</tr>
<tr>
<td>X.Y</td>
<td>未指定</td>
<td>DEBUG</td>
</tr>
<tr>
<td>X.Y.Z</td>
<td>未指定</td>
<td>DEBUG</td>
</tr>
</tbody></table>
<p>【例2】各自都指定了级别，那么以指定的日志级别为主</p>
<table>
<thead>
<tr>
<th>Logger 名称</th>
<th>指定的级别</th>
<th>实际的级别</th>
</tr>
</thead>
<tbody><tr>
<td>root</td>
<td>DEBUG（默认）</td>
<td>DEBUG</td>
</tr>
<tr>
<td>X</td>
<td>INFO</td>
<td>INFO</td>
</tr>
<tr>
<td>X.Y</td>
<td>DEBUG</td>
<td>DEBUG</td>
</tr>
<tr>
<td>X.Y.Z</td>
<td>WARN</td>
<td>WARN</td>
</tr>
</tbody></table>
<p>【例3】当未指定级别时，将继承父节点的日志级别</p>
<table>
<thead>
<tr>
<th>Logger 名称</th>
<th>指定的级别</th>
<th>实际的级别</th>
</tr>
</thead>
<tbody><tr>
<td>root</td>
<td>DEBUG（默认）</td>
<td>DEBUG</td>
</tr>
<tr>
<td>X</td>
<td>INFO</td>
<td>INFO</td>
</tr>
<tr>
<td>X.Y</td>
<td>未指定</td>
<td>INFO</td>
</tr>
<tr>
<td>X.Y.Z</td>
<td>ERROR</td>
<td>ERROR</td>
</tr>
</tbody></table>
<p>【例4】当未指定级别，且父节点也未指定级别时，继续向上查找</p>
<table>
<thead>
<tr>
<th>Logger 名称</th>
<th>指定的级别</th>
<th>实际的级别</th>
</tr>
</thead>
<tbody><tr>
<td>root</td>
<td>DEBUG（默认）</td>
<td>DEBUG</td>
</tr>
<tr>
<td>X</td>
<td>INFO</td>
<td>INFO</td>
</tr>
<tr>
<td>X.Y</td>
<td>未指定</td>
<td>INFO</td>
</tr>
<tr>
<td>X.Y.Z</td>
<td>未指定</td>
<td>INFO</td>
</tr>
</tbody></table>
<h2 id="2-4-logback-中日志打印方式以及基本的选择规则"><a href="#2-4-logback-中日志打印方式以及基本的选择规则" class="headerlink" title="2.4 logback 中日志打印方式以及基本的选择规则"></a>2.4 logback 中日志打印方式以及基本的选择规则</h2><p><strong>日志打印方式</strong></p>
<p>直接调用 Logger 接口对应日志级别的方法，比如，logger.info(“..”) 就是打印 INFO 级别的 Logger 语句。</p>
<p><strong>选择规则</strong></p>
<p>日志级别高的 Logger 对象，会默认开启相等和更低的日志级别，例如，DEBUG级别的 Logger 在执行 logger.info(“..”) 方法时也是有效的，因为 DEBUG的级别大于 INFO<br>logback 中的日志级别排序为：<br>TRACE &lt; <strong>DEBUG</strong> &lt; INFO &lt; WARN &lt; ERROR<br>将日志是否支持打印制成一张二维表如下：</p>
<table>
<thead>
<tr>
<th align="left">调用的日志级别</th>
<th align="left">定义的日志级别</th>
<th align="left">定义的日志级别</th>
<th align="left">定义的日志级别</th>
<th align="left">定义的日志级别</th>
<th align="left">定义的日志级别</th>
<th align="left">定义的日志级别</th>
</tr>
</thead>
<tbody><tr>
<td align="left"></td>
<td align="left">TRACE</td>
<td align="left">DEBUG</td>
<td align="left">INFO</td>
<td align="left">WARN</td>
<td align="left">ERROR</td>
<td align="left">OFF（关闭）</td>
</tr>
<tr>
<td align="left">TRACE</td>
<td align="left">支持</td>
<td align="left">不支持</td>
<td align="left">不支持</td>
<td align="left">不支持</td>
<td align="left">不支持</td>
<td align="left">不支持</td>
</tr>
<tr>
<td align="left">DEBUG</td>
<td align="left">支持</td>
<td align="left">支持</td>
<td align="left">不支持</td>
<td align="left">不支持</td>
<td align="left">不支持</td>
<td align="left">不支持</td>
</tr>
<tr>
<td align="left">INFO</td>
<td align="left">支持</td>
<td align="left">支持</td>
<td align="left">支持</td>
<td align="left">不支持</td>
<td align="left">不支持</td>
<td align="left">不支持</td>
</tr>
<tr>
<td align="left">WARN</td>
<td align="left">支持</td>
<td align="left">支持</td>
<td align="left">支持</td>
<td align="left">支持</td>
<td align="left">不支持</td>
<td align="left">不支持</td>
</tr>
<tr>
<td align="left">ERROR</td>
<td align="left">支持</td>
<td align="left">支持</td>
<td align="left">支持</td>
<td align="left">支持</td>
<td align="left">支持</td>
<td align="left">不支持</td>
</tr>
</tbody></table>
<h1 id="三、logback-配置"><a href="#三、logback-配置" class="headerlink" title="三、logback 配置"></a>三、logback 配置</h1><hr>
<p>官方文档：<a target="_blank" rel="noopener" href="https://logback.qos.ch/manual/configuration.html">https://logback.qos.ch/manual/configuration.html</a></p>
<p>官方支持将 log4j.properties 转化为 logback.xml 的页面：<a target="_blank" rel="noopener" href="https://logback.qos.ch/translator/">https://logback.qos.ch/translator/</a></p>
<h2 id="3-1-配置流程"><a href="#3-1-配置流程" class="headerlink" title="3.1 配置流程"></a>3.1 配置流程</h2><p>logback 配置初始化流程【参照官方】</p>
<ol>
<li><p>从 classpath 类路径下查找 <code>logback-test.xml</code>文件</p>
</li>
<li><p>若没找到文件，则继续在 classpath 类路径下查找 <code>logback.xml</code></p>
</li>
<li><p>若依然没找到文件，则通过<a target="_blank" rel="noopener" href="https://docs.oracle.com/javase/6/docs/api/java/util/ServiceLoader.html"> java.util.ServiceLoader</a> 类（JDK1.6引入），通过查找 <code>META-INF\services\ch.qos.logback.classic.spi.Configurator</code>来解析接口的实现类路径，根据实现类进行配置</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> ch.qos.logback.classic.spi;<br><br><span class="hljs-keyword">import</span> ch.qos.logback.classic.LoggerContext;<br><span class="hljs-keyword">import</span> ch.qos.logback.core.spi.ContextAware;<br><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title class_">Configurator</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_">ContextAware</span> &#123;<br>    <span class="hljs-keyword">void</span> <span class="hljs-title function_">configure</span><span class="hljs-params">(LoggerContext var1)</span>;<br>&#125;<br><br></code></pre></td></tr></table></figure>
</li>
<li><p>若上方的指定目录下不存在 Configurator 接口实现类，logback则开始自动配置，通过 ch.qos.logback.classic.BasicConfigurator 类进行自动配置，默认将日志输出设置为打印到控制台。</p>
</li>
</ol>
<h2 id="3-2-自定义配置的三种方式"><a href="#3-2-自定义配置的三种方式" class="headerlink" title="3.2 自定义配置的三种方式"></a>3.2 自定义配置的三种方式</h2><h3 id="3-2-1-硬编码"><a href="#3-2-1-硬编码" class="headerlink" title="3.2.1 硬编码"></a>3.2.1 硬编码</h3><ul>
<li>方式一：通过硬编码创建两种不同类的对应 Logger<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">import</span> org.slf4j.Logger;<br><span class="hljs-keyword">import</span> org.slf4j.LoggerFactory;<br><br><span class="hljs-keyword">class</span> <span class="hljs-title class_">Student</span>&#123;<br>    <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-type">Logger</span> <span class="hljs-variable">logger</span> <span class="hljs-operator">=</span> LoggerFactory.getLogger(Student.class);<br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">study</span><span class="hljs-params">()</span>&#123;<br>        logger.info(<span class="hljs-string">&quot;Student: studying... &quot;</span>);<br>    &#125;<br>&#125;<br><span class="hljs-keyword">class</span> <span class="hljs-title class_">Teacher</span>&#123;<br>    <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-type">Logger</span> <span class="hljs-variable">logger</span> <span class="hljs-operator">=</span> LoggerFactory.getLogger(Teacher.class);<br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">teach</span><span class="hljs-params">()</span>&#123;<br>        logger.info(<span class="hljs-string">&quot;Teacher: teaching...&quot;</span>);<br>    &#125;<br>&#125;<br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">LogbackDemo</span>&#123;<br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">main</span><span class="hljs-params">(String[] args)</span> &#123;<br>        <span class="hljs-type">Student</span> <span class="hljs-variable">student</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Student</span>();<br>        <span class="hljs-type">Teacher</span> <span class="hljs-variable">teacher</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Teacher</span>();<br>        teacher.teach();<br>        student.study();<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>
<blockquote>
<p>&#x3D;&#x3D;运行结果&#x3D;&#x3D;<br>13:36:27.750 [main] INFO Teacher - Teacher: teaching…<br>13:36:27.754 [main] INFO Student - Student: studying…</p>
</blockquote>
</li>
</ul>
<p>这种方式并没有依赖 Logback，因为 logback-classic 实现了 slf4j ，所以这种方式的代码可以切换到不同的日志框架。</p>
<h3 id="3-2-2-通过-logback-test-xml-或-logback-xml"><a href="#3-2-2-通过-logback-test-xml-或-logback-xml" class="headerlink" title="3.2.2 通过 logback-test.xml 或 logback.xml"></a>3.2.2 通过 logback-test.xml 或 logback.xml</h3><p>根据之前 logback的配置流程，我们可以创建配置文件来配置 Logger ，如：<br>配置日志打印到控制台的格式</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">configuration</span>&gt;</span><br><br>  <span class="hljs-tag">&lt;<span class="hljs-name">appender</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;STDOUT&quot;</span> <span class="hljs-attr">class</span>=<span class="hljs-string">&quot;ch.qos.logback.core.ConsoleAppender&quot;</span>&gt;</span><br>    <span class="hljs-comment">&lt;!-- 分配编码器的类型</span><br><span class="hljs-comment">        默认为 ch.qos.logback.classic.encoder.PatternLayoutEncoder  --&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">encoder</span>&gt;</span><br>      <span class="hljs-tag">&lt;<span class="hljs-name">pattern</span>&gt;</span>%d&#123;HH:mm:ss.SSS&#125; [%thread] %-5level %logger&#123;36&#125; - %msg%n<span class="hljs-tag">&lt;/<span class="hljs-name">pattern</span>&gt;</span><br>    <span class="hljs-tag">&lt;/<span class="hljs-name">encoder</span>&gt;</span><br>  <span class="hljs-tag">&lt;/<span class="hljs-name">appender</span>&gt;</span><br><br>  <span class="hljs-tag">&lt;<span class="hljs-name">root</span> <span class="hljs-attr">level</span>=<span class="hljs-string">&quot;debug&quot;</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">appender-ref</span> <span class="hljs-attr">ref</span>=<span class="hljs-string">&quot;STDOUT&quot;</span> /&gt;</span><br>  <span class="hljs-tag">&lt;/<span class="hljs-name">root</span>&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">configuration</span>&gt;</span><br></code></pre></td></tr></table></figure>
<h3 id="3-2-3-监听器配置"><a href="#3-2-3-监听器配置" class="headerlink" title="3.2.3 监听器配置"></a>3.2.3 监听器配置</h3><p>logback 支持监听器配置，即在日志所存储的空间不足或由于权限错误而无法归档时，例：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">configuration</span>&gt;</span> <br>  &lt;-- 建议：将状态监听器放在配置文件的顶部 --&gt; <br>  <span class="hljs-tag">&lt;<span class="hljs-name">statusListener</span> <span class="hljs-attr">class</span> = <span class="hljs-string">&quot;ch.qos.logback.core.status.OnConsoleStatusListener&quot;</span> /&gt;</span>  <br><br>   ... 配置文件的其余部分<br><span class="hljs-tag">&lt;/<span class="hljs-name">配置</span>&gt;</span><br></code></pre></td></tr></table></figure>
<p>关于 logback 的配置我们暂时了解到这，本次主要了解的是其内部用到的工厂设计模式</p>
<h1 id="四、logback-使用案例"><a href="#四、logback-使用案例" class="headerlink" title="四、logback 使用案例"></a>四、logback 使用案例</h1><hr>
<p>我们使用目前最稳定的 logback 版本 v1.2.11</p>
<p><strong>引入 Maven 依赖</strong></p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><code class="hljs xml"><span class="hljs-meta">&lt;?xml version=<span class="hljs-string">&quot;1.0&quot;</span> encoding=<span class="hljs-string">&quot;UTF-8&quot;</span>?&gt;</span><br><span class="hljs-tag">&lt;<span class="hljs-name">project</span> <span class="hljs-attr">xmlns</span>=<span class="hljs-string">&quot;http://maven.apache.org/POM/4.0.0&quot;</span></span><br><span class="hljs-tag">         <span class="hljs-attr">xmlns:xsi</span>=<span class="hljs-string">&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span></span><br><span class="hljs-tag">         <span class="hljs-attr">xsi:schemaLocation</span>=<span class="hljs-string">&quot;http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd&quot;</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">modelVersion</span>&gt;</span>4.0.0<span class="hljs-tag">&lt;/<span class="hljs-name">modelVersion</span>&gt;</span><br><br>    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>com.uni<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>logback-demo<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>1.0-SNAPSHOT<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span><br><br>    <span class="hljs-tag">&lt;<span class="hljs-name">properties</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">maven.compiler.source</span>&gt;</span>8<span class="hljs-tag">&lt;/<span class="hljs-name">maven.compiler.source</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">maven.compiler.target</span>&gt;</span>8<span class="hljs-tag">&lt;/<span class="hljs-name">maven.compiler.target</span>&gt;</span><br>    <span class="hljs-tag">&lt;/<span class="hljs-name">properties</span>&gt;</span><br><br><br>    <span class="hljs-tag">&lt;<span class="hljs-name">dependencies</span>&gt;</span><br>        <span class="hljs-comment">&lt;!-- https://mvnrepository.com/artifact/ch.qos.logback/logback-core --&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span><br>            <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>ch.qos.logback<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span><br>            <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>logback-core<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span><br>            <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>1.2.11<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span><br>        <span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span><br><br><br>        <span class="hljs-comment">&lt;!-- https://mvnrepository.com/artifact/ch.qos.logback/logback-classic --&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span><br>            <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>ch.qos.logback<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span><br>            <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>logback-classic<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span><br>            <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>1.2.11<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span><br>        <span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span><br><br>    <span class="hljs-tag">&lt;/<span class="hljs-name">dependencies</span>&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">project</span>&gt;</span><br></code></pre></td></tr></table></figure>
<p><strong>编写测试类</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">import</span> org.slf4j.Logger;<br><span class="hljs-keyword">import</span> org.slf4j.LoggerFactory;<br><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">LogbackDemo</span> &#123;<br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">main</span><span class="hljs-params">(String[] args)</span> &#123;<br>        <span class="hljs-type">Logger</span> <span class="hljs-variable">log</span> <span class="hljs-operator">=</span> LoggerFactory.getLogger(LogbackDemo.class);<br>        log.debug(<span class="hljs-string">&quot;【debug】 hello, logback!&quot;</span>);<br>        log.error(<span class="hljs-string">&quot;【error】 hello, logback!&quot;</span>);<br>        log.info(<span class="hljs-string">&quot;【info】 hello, logback!&quot;</span>);<br>        log.warn(<span class="hljs-string">&quot;【warn】 hello, logback!&quot;</span>);<br>        log.trace(<span class="hljs-string">&quot;默认级别是DEBUG,所以这行不会输出【trace】hello, logback!&quot;</span>);<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>
<blockquote>
<p>&#x3D;&#x3D;运行结果&#x3D;&#x3D;<br>10:33:28.744 [main] DEBUG LogbackDemo - 【debug】 hello, logback!<br>10:33:28.747 [main] ERROR LogbackDemo - 【error】 hello, logback!<br>10:33:28.747 [main] INFO LogbackDemo - 【info】 hello, logback!<br>10:33:28.747 [main] WARN LogbackDemo - 【warn】 hello, logback!</p>
</blockquote>
<p>在 logback 的使用中，我们通常通过 LoggerFactory 日志工厂来获取指定类的 Logger对象，比如在上面的例子中就是在 主函数中获取 LogbackDemo类的对应日志对象 Logger</p>
<p>除了简单的获取 Logger 日志对象以外，我们还可以获取 日志工厂的应用上下文，如：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-type">LoggerContext</span> <span class="hljs-variable">lc</span>  <span class="hljs-operator">=</span> (LoggerContext) LoggerFactory.getILoggerFactory();<br></code></pre></td></tr></table></figure>
<h1 id="五、logback-中的工厂方法模式与单例模式"><a href="#五、logback-中的工厂方法模式与单例模式" class="headerlink" title="五、logback 中的工厂方法模式与单例模式"></a>五、logback 中的工厂方法模式与单例模式</h1><hr>
<p>根据之前的例子，Logback 在创建 Logger 时，使用的就是 LoggerFactory 的 getLogger 方法</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">LoggerFactory</span> &#123;<br>    <span class="hljs-keyword">private</span> <span class="hljs-title function_">LoggerFactory</span><span class="hljs-params">()</span> &#123;&#125;		<span class="hljs-comment">// 构造方法私有化</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Logger <span class="hljs-title function_">getLogger</span><span class="hljs-params">(Class&lt;?&gt; clazz)</span> &#123;<br>        ...<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>
<p>接下来我们查看 Logback中获取Logger对象的源码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Logger <span class="hljs-title function_">getLogger</span><span class="hljs-params">(Class&lt;?&gt; clazz)</span> &#123;<br>    <span class="hljs-comment">// 获取字节码的名称，调用重载方法获取 Logger</span><br>    <span class="hljs-type">Logger</span> <span class="hljs-variable">logger</span> <span class="hljs-operator">=</span> getLogger(clazz.getName());<br>    <span class="hljs-comment">// 如果Logger名称不匹配，则打印提示信息</span><br>    <span class="hljs-keyword">if</span> (DETECT_LOGGER_NAME_MISMATCH) &#123;<br>        Class&lt;?&gt; autoComputedCallingClass = Util.getCallingClass();<br>        <span class="hljs-keyword">if</span> (autoComputedCallingClass != <span class="hljs-literal">null</span> &amp;&amp; nonMatchingClasses(clazz, autoComputedCallingClass)) &#123;<br>            Util.report(String.format(<span class="hljs-string">&quot;Detected logger name mismatch. Given name: \&quot;%s\&quot;; computed name: \&quot;%s\&quot;.&quot;</span>, logger.getName(),<br>                                      autoComputedCallingClass.getName()));<br>            Util.report(<span class="hljs-string">&quot;See &quot;</span> + LOGGER_NAME_MISMATCH_URL + <span class="hljs-string">&quot; for an explanation&quot;</span>);<br>        &#125;<br>    &#125;<br>    <span class="hljs-keyword">return</span> logger;<br>&#125;<br><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Logger <span class="hljs-title function_">getLogger</span><span class="hljs-params">(String name)</span> &#123;<br>    <span class="hljs-comment">// 获取工厂实现类</span><br>    <span class="hljs-type">ILoggerFactory</span> <span class="hljs-variable">iLoggerFactory</span> <span class="hljs-operator">=</span> getILoggerFactory();<br>    <span class="hljs-keyword">return</span> iLoggerFactory.getLogger(name);<br>&#125;<br><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> ILoggerFactory <span class="hljs-title function_">getILoggerFactory</span><span class="hljs-params">()</span> &#123;<br>    <span class="hljs-comment">// 判断 LoggerFactory是否初始化过 static volatile int INITIALIZATION_STATE = UNINITIALIZED;</span><br>    <span class="hljs-keyword">if</span> (INITIALIZATION_STATE == UNINITIALIZED) &#123;<br>        <span class="hljs-comment">// 若未初始化则锁资源</span><br>        <span class="hljs-keyword">synchronized</span> (LoggerFactory.class) &#123;<br>            <span class="hljs-comment">// 双重判断</span><br>            <span class="hljs-keyword">if</span> (INITIALIZATION_STATE == UNINITIALIZED) &#123;<br>                <span class="hljs-comment">// 修改初始化状态</span><br>                INITIALIZATION_STATE = ONGOING_INITIALIZATION;<br>                <span class="hljs-comment">// 调用本地的初始化方法</span><br>                performInitialization();<br>            &#125;<br>        &#125;<br>    &#125;<br>    <span class="hljs-comment">// 判断工厂的初始化状态</span><br>    <span class="hljs-keyword">switch</span> (INITIALIZATION_STATE) &#123;<br>        <span class="hljs-comment">// 情况1: 已成功初始化, 通过 StaticLoggerBinder Logger的静态绑定类来获取单例的工厂</span><br>        <span class="hljs-keyword">case</span> SUCCESSFUL_INITIALIZATION:<br>            <span class="hljs-keyword">return</span> StaticLoggerBinder.getSingleton().getLoggerFactory();<br>        <span class="hljs-comment">// 情况2: 初始化失败并回调，返回一个已经定义好的 NOPLoggerFactory工厂对象</span><br>        <span class="hljs-keyword">case</span> NOP_FALLBACK_INITIALIZATION:<br>            <span class="hljs-keyword">return</span> NOP_FALLBACK_FACTORY;<br>        <span class="hljs-comment">// 情况3: 初始化失败, 没有回调, 直接抛异常</span><br>        <span class="hljs-keyword">case</span> FAILED_INITIALIZATION:<br>            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">IllegalStateException</span>(UNSUCCESSFUL_INIT_MSG);<br>        <span class="hljs-comment">// 情况4: 重新调用getLogger(), 返回 SubstituteLoggerFactory工厂对象</span><br>        <span class="hljs-keyword">case</span> ONGOING_INITIALIZATION:<br>            <span class="hljs-comment">// 官方说明 http://jira.qos.ch/browse/SLF4J-97</span><br>            <span class="hljs-keyword">return</span> SUBST_FACTORY;<br>    &#125;<br>    <span class="hljs-comment">// 最后若都没有返回或抛出异常，则最后抛出异常</span><br>    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">IllegalStateException</span>(<span class="hljs-string">&quot;Unreachable code&quot;</span>);<br>&#125;<br></code></pre></td></tr></table></figure>
<p>通过上方的源码，我们可以知道 LoggerFactory 是不可继承以及不可以实例化的工厂类，它提供了 getLogger() 方法来获取 Logger 日志对象，工厂方法模式的主要实现是在获取Logger工厂的方法里</p>
<p> <code>public static ILoggerFactory getILoggerFactory()</code></p>
<p>在 <code>getILoggerFactory() </code> 方法中先判断是否工厂已经初始化，然后根据初始化后的不同状态返回对应的工厂示例，符合工厂方法模式的设计思路。</p>
<p>除了工厂模式以外，这里面在判断工厂初始化状态时还用到了单例模式中的懒汉式，同时使用了 <code>volatine</code> 定义变量，使用 <code>synchronized</code> 进行同步。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-type">int</span> <span class="hljs-variable">UNINITIALIZED</span> <span class="hljs-operator">=</span> <span class="hljs-number">0</span>;<br><br><span class="hljs-keyword">static</span> <span class="hljs-keyword">volatile</span> <span class="hljs-type">int</span> <span class="hljs-variable">INITIALIZATION_STATE</span> <span class="hljs-operator">=</span> UNINITIALIZED;<br></code></pre></td></tr></table></figure>
<p>这里用到了双重判断，考虑了在多线程的开发环境下，多个线程可能会等待抢占锁，并等待释放而浪费资源。<br>以下就是单例模式的标准用法，由于初始化的值为0，故可视为懒汉式，当在调用的时候才赋值为状态值。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">if</span> (INITIALIZATION_STATE == UNINITIALIZED) &#123;<br>    <span class="hljs-comment">// 若未初始化则锁资源</span><br>    <span class="hljs-keyword">synchronized</span> (LoggerFactory.class) &#123;<br>        <span class="hljs-comment">// 双重判断</span><br>        <span class="hljs-keyword">if</span> (INITIALIZATION_STATE == UNINITIALIZED) &#123;<br>            <span class="hljs-comment">// 修改初始化状态</span><br>            INITIALIZATION_STATE = ONGOING_INITIALIZATION;<br>            <span class="hljs-comment">// 调用本地的初始化方法</span><br>            performInitialization();<br>        &#125;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>
<p>由此可见，在源码中经常是存在设计模式的，这里用到了工厂方法模式，又用到了单例模式，学习好设计模式对阅读源码是有一定的帮助的。本次没有记录多少关于 logback的使用，主要是介绍了它的一些概念与架构，暂时先以了解为主吧，目前暂时没有用到，之后遇到的时候在好好学一学。</p>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/categories/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/" class="category-chain-item">设计模式</a>
  
  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/tags/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/">#设计模式</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>设计模式 笔记5 _ 工厂方法模式 在源码中的应用 _ logback 日志管理框架含义、架构以及配置 _ logback 使用案例 _ logback中存在的工厂方法模式和单例模式 _</div>
      <div>http://example.com/2022/07/21/设计模式 笔记5 _ 工厂方法模式 在源码中的应用 _ logback 日志管理框架含义、架构以及配置 _ logback 使用案例 _ logback中存在的工厂方法模式和单例模式 _/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>John Doe</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2022年7月21日</div>
        </div>
      
      
      <div class="license-meta-item">
        <div>许可协议</div>
        <div>
          
            
            
              <a target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
              <span class="hint--top hint--rounded" aria-label="BY - 署名">
                <i class="iconfont icon-by"></i>
              </span>
              </a>
            
          
        </div>
      </div>
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2022/07/21/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F%20%E7%AC%94%E8%AE%B04%20_%20%E7%AE%80%E5%8D%95%E5%B7%A5%E5%8E%82%E6%A8%A1%E5%BC%8F%20%E5%9C%A8%E6%BA%90%E7%A0%81%E4%B8%AD%E7%9A%84%E5%BA%94%E7%94%A8%20_%20Calendar%20%E6%97%A5%E5%8E%86%20_%20%E6%BA%90%E7%A0%81%E6%B5%85%E6%9E%90%20_%20%E4%BD%BF%E7%94%A8%E6%80%BB%E7%BB%93%20_%20%E5%BB%BA%E9%80%A0%E8%80%85%E6%A8%A1%E5%BC%8F/" title="设计模式 笔记4 _ 简单工厂模式 在源码中的应用 _ Calendar 日历 _ 源码浅析 _ 使用总结 _ 建造者模式">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">设计模式 笔记4 _ 简单工厂模式 在源码中的应用 _ Calendar 日历 _ 源码浅析 _ 使用总结 _ 建造者模式</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2022/07/19/Spring%20Cloud%20%E6%9C%8D%E5%8A%A1%E6%B3%A8%E5%86%8C%E7%AC%94%E8%AE%B03%20Consul%20%E4%BD%9C%E4%B8%BA%E6%9C%8D%E5%8A%A1%E6%B3%A8%E5%86%8C%E4%B8%AD%E5%BF%83/" title="Spring Cloud 服务注册笔记3 Consul 作为服务注册中心">
                        <span class="hidden-mobile">Spring Cloud 服务注册笔记3 Consul 作为服务注册中心</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
    </div>
  
  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      headingSelector : CONFIG.toc.headingSelector || 'h1,h2,h3,h4,h5,h6',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      collapseDepth   : CONFIG.toc.collapseDepth || 0,
      scrollSmooth    : true,
      headingsOffset  : -boardTop
    });
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.10/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script  src="/js/local-search.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
